package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;


@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

//    @Autowired
//    private RedissonClient redisson;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redisson;
    @GetMapping({"/","index.html"}) // 爆404
//    @GetMapping("/")

    private String indexPage(Model model) {

        //1、查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categories",categoryEntities);
        return "index";
    }
    //"index/catalog.json"
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1. 获取一把锁
        RLock redissonLock = redisson.getLock("my-lock");
        //2. 加锁代码

        redissonLock.lock(); //阻塞式等待...
        try{
            System.out.println("枷锁成功，执行业务" + Thread.currentThread().getId());
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //3. 调用解锁
            System.out.println("释放锁.." + Thread.currentThread().getId());
            redissonLock.unlock();
        }

        return "hello";
    }
}
